
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" lang="zh_Hans">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>单元测试集 &#8212; Django 3.2.11.dev 文档</title>
    <link rel="stylesheet" href="../../../_static/default.css" type="text/css" />
    <link rel="stylesheet" href="../../../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../../../" src="../../../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../../../_static/jquery.js"></script>
    <script type="text/javascript" src="../../../_static/underscore.js"></script>
    <script type="text/javascript" src="../../../_static/doctools.js"></script>
    <script type="text/javascript" src="../../../_static/language_data.js"></script>
    <link rel="index" title="索引" href="../../../genindex.html" />
    <link rel="search" title="搜索" href="../../../search.html" />
    <link rel="next" title="提交补丁" href="submitting-patches.html" />
    <link rel="prev" title="编码风格" href="coding-style.html" />



 
<script src="../../../templatebuiltins.js"></script>
<script>
(function($) {
    if (!django_template_builtins) {
       // templatebuiltins.js missing, do nothing.
       return;
    }
    $(document).ready(function() {
        // Hyperlink Django template tags and filters
        var base = "../../../ref/templates/builtins.html";
        if (base == "#") {
            // Special case for builtins.html itself
            base = "";
        }
        // Tags are keywords, class '.k'
        $("div.highlight\\-html\\+django span.k").each(function(i, elem) {
             var tagname = $(elem).text();
             if ($.inArray(tagname, django_template_builtins.ttags) != -1) {
                 var fragment = tagname.replace(/_/, '-');
                 $(elem).html("<a href='" + base + "#" + fragment + "'>" + tagname + "</a>");
             }
        });
        // Filters are functions, class '.nf'
        $("div.highlight\\-html\\+django span.nf").each(function(i, elem) {
             var filtername = $(elem).text();
             if ($.inArray(filtername, django_template_builtins.tfilters) != -1) {
                 var fragment = filtername.replace(/_/, '-');
                 $(elem).html("<a href='" + base + "#" + fragment + "'>" + filtername + "</a>");
             }
        });
    });
})(jQuery);(function($) {
    $(document).ready(function() {
        $(".c-tab-unix").on("click", function() {
            $("section.c-content-unix").show();
            $("section.c-content-win").hide();
            $(".c-tab-unix").prop("checked", true);
        });
        $(".c-tab-win").on("click", function() {
            $("section.c-content-win").show();
            $("section.c-content-unix").hide();
            $(".c-tab-win").prop("checked", true);
        });
    });
})(jQuery);</script>
<link rel="stylesheet" href="../../../_static/console-tabs.css" type="text/css" />
  </head><body>

    <div class="document">
  <div id="custom-doc" class="yui-t6">
    <div id="hd">
      <h1><a href="../../../index.html">Django 3.2.11.dev 文档</a></h1>
      <div id="global-nav">
        <a title="Home page" href="../../../index.html">Home</a>  |
        <a title="Table of contents" href="../../../contents.html">Table of contents</a>  |
        <a title="Global index" href="../../../genindex.html">Index</a>  |
        <a title="Module index" href="../../../py-modindex.html">Modules</a>
      </div>
      <div class="nav">
    &laquo; <a href="coding-style.html" title="编码风格">previous</a>
     |
    <a href="../../index.html" title="Django internals" accesskey="U">up</a>
   |
    <a href="submitting-patches.html" title="提交补丁">next</a> &raquo;</div>
    </div>

    <div id="bd">
      <div id="yui-main">
        <div class="yui-b">
          <div class="yui-g" id="internals-contributing-writing-code-unit-tests">
            
  <div class="section" id="s-unit-tests">
<span id="unit-tests"></span><h1>单元测试集<a class="headerlink" href="#unit-tests" title="永久链接至标题">¶</a></h1>
<p>Django在代码基本库的 <code class="docutils literal notranslate"><span class="pre">tests</span></code> 目录中带有自己的测试套件。 我们的政策是确保所有测试始终通过。</p>
<p>我们感谢对测试套件的所有贡献！</p>
<p>The Django tests all use the testing infrastructure that ships with Django for
testing applications. See <a class="reference internal" href="../../../topics/testing/overview.html"><span class="doc">编写并运行测试</span></a> for an explanation of
how to write new tests.</p>
<div class="section" id="s-running-the-unit-tests">
<span id="s-running-unit-tests"></span><span id="running-the-unit-tests"></span><span id="running-unit-tests"></span><h2>运行单元测试<a class="headerlink" href="#running-the-unit-tests" title="永久链接至标题">¶</a></h2>
<div class="section" id="s-quickstart">
<span id="quickstart"></span><h3>快速上手<a class="headerlink" href="#quickstart" title="永久链接至标题">¶</a></h3>
<p>First, <a class="reference external" href="https://github.com/django/django/fork">fork Django on GitHub</a>.</p>
<p>Second, create and activate a virtual environment. If you're not familiar with
how to do that, read our <a class="reference internal" href="../../../intro/contributing.html"><span class="doc">contributing tutorial</span></a>.</p>
<p>Next, clone your fork, install some requirements, and run the tests:</p>
<div class="console-block" id="console-block-0">
<input class="c-tab-unix" id="c-tab-0-unix" type="radio" name="console-0" checked>
<label for="c-tab-0-unix" title="Linux/macOS">&#xf17c/&#xf179</label>
<input class="c-tab-win" id="c-tab-0-win" type="radio" name="console-0">
<label for="c-tab-0-win" title="Windows">&#xf17a</label>
<section class="c-content-unix" id="c-content-0-unix">
<div class="highlight-console notranslate"><div class="highlight"><pre><span></span><span class="gp">$ </span>git clone https://github.com/YourGitHubName/django.git django-repo
<span class="gp">$ </span><span class="nb">cd</span> django-repo/tests
<span class="gp">$ </span>python -m pip install -e ..
<span class="gp">$ </span>python -m pip install -r requirements/py3.txt
<span class="gp">$ </span>./runtests.py
</pre></div>
</div>
</section>
<section class="c-content-win" id="c-content-0-win">
<div class="highlight"><pre><span></span><span class="gp">...\&gt;</span> git clone https://github.com/YourGitHubName/django.git django-repo
<span class="gp">...\&gt;</span> <span class="k">cd</span> django-repo\tests
<span class="gp">...\&gt;</span> py -m pip install -e ..
<span class="gp">...\&gt;</span> py -m pip install -r requirements\py3.txt
<span class="gp">...\&gt;</span> runtests.py 
</pre></div>
</section>
</div>
<p>Installing the requirements will likely require some operating system packages
that your computer doesn't have installed. You can usually figure out which
package to install by doing a Web search for the last line or so of the error
message. Try adding your operating system to the search query if needed.</p>
<p>If you have trouble installing the requirements, you can skip that step. See
<a class="reference internal" href="#running-unit-tests-dependencies"><span class="std std-ref">运行所有测试</span></a> for details on installing the optional
test dependencies. If you don't have an optional dependency installed, the
tests that require it will be skipped.</p>
<p>Running the tests requires a Django settings module that defines the databases
to use. To help you get started, Django provides and uses a sample settings
module that uses the SQLite database. See <a class="reference internal" href="#running-unit-tests-settings"><span class="std std-ref">使用另一个 settings 配置模块</span></a> to
learn how to use a different settings module to run the tests with a different
database.</p>
<p>Having problems? See <a class="reference internal" href="#troubleshooting-unit-tests"><span class="std std-ref">错误调试</span></a> for some common issues.</p>
</div>
<div class="section" id="s-running-tests-using-tox">
<span id="running-tests-using-tox"></span><h3>Running tests using <code class="docutils literal notranslate"><span class="pre">tox</span></code><a class="headerlink" href="#running-tests-using-tox" title="永久链接至标题">¶</a></h3>
<p><a class="reference external" href="https://tox.readthedocs.io/">Tox</a> is a tool for running tests in different
virtual environments. Django includes a basic <code class="docutils literal notranslate"><span class="pre">tox.ini</span></code> that automates some
checks that our build server performs on pull requests. To run the unit tests
and other checks (such as <a class="reference internal" href="coding-style.html#coding-style-imports"><span class="std std-ref">import sorting</span></a>, the
<a class="reference internal" href="../writing-documentation.html#documentation-spelling-check"><span class="std std-ref">documentation spelling checker</span></a>, and
<a class="reference internal" href="coding-style.html#coding-style-python"><span class="std std-ref">code formatting</span></a>), install and run the <code class="docutils literal notranslate"><span class="pre">tox</span></code>
command from any place in the Django source tree:</p>
<div class="console-block" id="console-block-1">
<input class="c-tab-unix" id="c-tab-1-unix" type="radio" name="console-1" checked>
<label for="c-tab-1-unix" title="Linux/macOS">&#xf17c/&#xf179</label>
<input class="c-tab-win" id="c-tab-1-win" type="radio" name="console-1">
<label for="c-tab-1-win" title="Windows">&#xf17a</label>
<section class="c-content-unix" id="c-content-1-unix">
<div class="highlight-console notranslate"><div class="highlight"><pre><span></span><span class="gp">$ </span>python -m pip install tox
<span class="gp">$ </span>tox
</pre></div>
</div>
</section>
<section class="c-content-win" id="c-content-1-win">
<div class="highlight"><pre><span></span><span class="gp">...\&gt;</span> py -m pip install tox
<span class="gp">...\&gt;</span> tox
</pre></div>
</section>
</div>
<p>By default, <code class="docutils literal notranslate"><span class="pre">tox</span></code> runs the test suite with the bundled test settings file for
SQLite, <code class="docutils literal notranslate"><span class="pre">flake8</span></code>, <code class="docutils literal notranslate"><span class="pre">isort</span></code>, and the documentation spelling checker. In
addition to the system dependencies noted elsewhere in this documentation,
the command <code class="docutils literal notranslate"><span class="pre">python3</span></code> must be on your path and linked to the appropriate
version of Python. A list of default environments can be seen as follows:</p>
<div class="console-block" id="console-block-2">
<input class="c-tab-unix" id="c-tab-2-unix" type="radio" name="console-2" checked>
<label for="c-tab-2-unix" title="Linux/macOS">&#xf17c/&#xf179</label>
<input class="c-tab-win" id="c-tab-2-win" type="radio" name="console-2">
<label for="c-tab-2-win" title="Windows">&#xf17a</label>
<section class="c-content-unix" id="c-content-2-unix">
<div class="highlight-console notranslate"><div class="highlight"><pre><span></span><span class="gp">$ </span>tox -l
<span class="go">py3</span>
<span class="go">flake8</span>
<span class="go">docs</span>
<span class="go">isort&gt;=5.1.0</span>
</pre></div>
</div>
</section>
<section class="c-content-win" id="c-content-2-win">
<div class="highlight"><pre><span></span><span class="gp">...\&gt;</span> tox -l
<span class="go">py3</span>
<span class="go">flake8</span>
<span class="go">docs</span>
<span class="gp">isort&gt;</span>=5.1.0
</pre></div>
</section>
</div>
<div class="section" id="s-testing-other-python-versions-and-database-backends">
<span id="testing-other-python-versions-and-database-backends"></span><h4>Testing other Python versions and database backends<a class="headerlink" href="#testing-other-python-versions-and-database-backends" title="永久链接至标题">¶</a></h4>
<p>In addition to the default environments, <code class="docutils literal notranslate"><span class="pre">tox</span></code> supports running unit tests
for other versions of Python and other database backends. Since Django's test
suite doesn't bundle a settings file for database backends other than SQLite,
however, you must <a class="reference internal" href="#running-unit-tests-settings"><span class="std std-ref">create and provide your own test settings</span></a>. For example, to run the tests on Python 3.7
using PostgreSQL:</p>
<div class="console-block" id="console-block-3">
<input class="c-tab-unix" id="c-tab-3-unix" type="radio" name="console-3" checked>
<label for="c-tab-3-unix" title="Linux/macOS">&#xf17c/&#xf179</label>
<input class="c-tab-win" id="c-tab-3-win" type="radio" name="console-3">
<label for="c-tab-3-win" title="Windows">&#xf17a</label>
<section class="c-content-unix" id="c-content-3-unix">
<div class="highlight-console notranslate"><div class="highlight"><pre><span></span><span class="gp">$ </span>tox -e py37-postgres -- --settings<span class="o">=</span>my_postgres_settings
</pre></div>
</div>
</section>
<section class="c-content-win" id="c-content-3-win">
<div class="highlight"><pre><span></span><span class="gp">...\&gt;</span> tox -e py37-postgres -- --settings=my_postgres_settings
</pre></div>
</section>
</div>
<p>This command sets up a Python 3.7 virtual environment, installs Django's
test suite dependencies (including those for PostgreSQL), and calls
<code class="docutils literal notranslate"><span class="pre">runtests.py</span></code> with the supplied arguments (in this case,
<code class="docutils literal notranslate"><span class="pre">--settings=my_postgres_settings</span></code>).</p>
<p>The remainder of this documentation shows commands for running tests without
<code class="docutils literal notranslate"><span class="pre">tox</span></code>, however, any option passed to <code class="docutils literal notranslate"><span class="pre">runtests.py</span></code> can also be passed to
<code class="docutils literal notranslate"><span class="pre">tox</span></code> by prefixing the argument list with <code class="docutils literal notranslate"><span class="pre">--</span></code>, as above.</p>
<p>Tox also respects the <span class="target" id="index-0"></span><a class="reference internal" href="../../../topics/settings.html#envvar-DJANGO_SETTINGS_MODULE"><code class="xref std std-envvar docutils literal notranslate"><span class="pre">DJANGO_SETTINGS_MODULE</span></code></a> environment variable, if
set. For example, the following is equivalent to the command above:</p>
<div class="highlight-console notranslate"><div class="highlight"><pre><span></span><span class="gp">$ </span><span class="nv">DJANGO_SETTINGS_MODULE</span><span class="o">=</span>my_postgres_settings tox -e py35-postgres
</pre></div>
</div>
<p>对于 Windows 用户应使用：</p>
<div class="highlight-doscon notranslate"><div class="highlight"><pre><span></span><span class="gp">...\&gt;</span> <span class="k">set</span> <span class="nv">DJANGO_SETTINGS_MODULE</span><span class="p">=</span>my_postgres_settings
<span class="gp">...\&gt;</span> tox -e py35-postgres
</pre></div>
</div>
</div>
<div class="section" id="s-running-the-javascript-tests">
<span id="running-the-javascript-tests"></span><h4>运行 JavaScript 测试集<a class="headerlink" href="#running-the-javascript-tests" title="永久链接至标题">¶</a></h4>
<p>Django includes a set of <a class="reference internal" href="javascript.html#javascript-tests"><span class="std std-ref">JavaScript unit tests</span></a> for
functions in certain contrib apps. The JavaScript tests aren't run by default
using <code class="docutils literal notranslate"><span class="pre">tox</span></code> because they require <code class="docutils literal notranslate"><span class="pre">Node.js</span></code> to be installed and aren't
necessary for the majority of patches. To run the JavaScript tests using
<code class="docutils literal notranslate"><span class="pre">tox</span></code>:</p>
<div class="console-block" id="console-block-4">
<input class="c-tab-unix" id="c-tab-4-unix" type="radio" name="console-4" checked>
<label for="c-tab-4-unix" title="Linux/macOS">&#xf17c/&#xf179</label>
<input class="c-tab-win" id="c-tab-4-win" type="radio" name="console-4">
<label for="c-tab-4-win" title="Windows">&#xf17a</label>
<section class="c-content-unix" id="c-content-4-unix">
<div class="highlight-console notranslate"><div class="highlight"><pre><span></span><span class="gp">$ </span>tox -e javascript
</pre></div>
</div>
</section>
<section class="c-content-win" id="c-content-4-win">
<div class="highlight"><pre><span></span><span class="gp">...\&gt;</span> tox -e javascript
</pre></div>
</section>
</div>
<p>This command runs <code class="docutils literal notranslate"><span class="pre">npm</span> <span class="pre">install</span></code> to ensure test requirements are up to
date and then runs <code class="docutils literal notranslate"><span class="pre">npm</span> <span class="pre">test</span></code>.</p>
</div>
</div>
<div class="section" id="s-running-tests-using-django-docker-box">
<span id="running-tests-using-django-docker-box"></span><h3>Running tests using <code class="docutils literal notranslate"><span class="pre">django-docker-box</span></code><a class="headerlink" href="#running-tests-using-django-docker-box" title="永久链接至标题">¶</a></h3>
<p><a class="reference external" href="https://github.com/django/django-docker-box/">django-docker-box</a> allows you to run the Django's test suite across all
supported databases and python versions. See the <a class="reference external" href="https://github.com/django/django-docker-box/">django-docker-box</a> project
page for installation and usage instructions.</p>
</div>
<div class="section" id="s-using-another-settings-module">
<span id="s-running-unit-tests-settings"></span><span id="using-another-settings-module"></span><span id="running-unit-tests-settings"></span><h3>使用另一个 <code class="docutils literal notranslate"><span class="pre">settings</span></code> 配置模块<a class="headerlink" href="#using-another-settings-module" title="永久链接至标题">¶</a></h3>
<p>The included settings module (<code class="docutils literal notranslate"><span class="pre">tests/test_sqlite.py</span></code>) allows you to run the
test suite using SQLite. If you want to run the tests using a different
database, you'll need to define your own settings file. Some tests, such as
those for <code class="docutils literal notranslate"><span class="pre">contrib.postgres</span></code>, are specific to a particular database backend
and will be skipped if run with a different backend. Some tests are skipped or
expected failures on a particular database backend (see
<code class="docutils literal notranslate"><span class="pre">DatabaseFeatures.django_test_skips</span></code> and
<code class="docutils literal notranslate"><span class="pre">DatabaseFeatures.django_test_expected_failures</span></code> on each backend).</p>
<p>To run the tests with different settings, ensure that the module is on your
<span class="target" id="index-1"></span><a class="reference external" href="https://docs.python.org/3/using/cmdline.html#envvar-PYTHONPATH" title="(在 Python v3.10)"><code class="xref std std-envvar docutils literal notranslate"><span class="pre">PYTHONPATH</span></code></a> and pass the module with <code class="docutils literal notranslate"><span class="pre">--settings</span></code>.</p>
<p>The <a class="reference internal" href="../../../ref/settings.html#std:setting-DATABASES"><code class="xref std std-setting docutils literal notranslate"><span class="pre">DATABASES</span></code></a> setting in any test settings module needs to define
two databases:</p>
<ul class="simple">
<li>A <code class="docutils literal notranslate"><span class="pre">default</span></code> database. This database should use the backend that
you want to use for primary testing.</li>
<li>A database with the alias <code class="docutils literal notranslate"><span class="pre">other</span></code>. The <code class="docutils literal notranslate"><span class="pre">other</span></code> database is used to test
that queries can be directed to different databases. This database should use
the same backend as the <code class="docutils literal notranslate"><span class="pre">default</span></code>, and it must have a different name.</li>
</ul>
<p>如果您使用的不是SQLite后端，则需要为每个数据库提供其他详细信息：</p>
<ul class="simple">
<li>The <a class="reference internal" href="../../../ref/settings.html#std:setting-USER"><code class="xref std std-setting docutils literal notranslate"><span class="pre">USER</span></code></a> option needs to specify an existing user account
for the database. That user needs permission to execute <code class="docutils literal notranslate"><span class="pre">CREATE</span> <span class="pre">DATABASE</span></code>
so that the test database can be created.</li>
<li><a class="reference internal" href="../../../ref/settings.html#std:setting-PASSWORD"><code class="xref std std-setting docutils literal notranslate"><span class="pre">PASSWORD</span></code></a> 配置选项需要为指定的配置:setting:<cite>USER</cite> 提供密码。</li>
</ul>
<p>Test databases get their names by prepending <code class="docutils literal notranslate"><span class="pre">test_</span></code> to the value of the
<a class="reference internal" href="../../../ref/settings.html#std:setting-NAME"><code class="xref std std-setting docutils literal notranslate"><span class="pre">NAME</span></code></a> settings for the databases defined in <a class="reference internal" href="../../../ref/settings.html#std:setting-DATABASES"><code class="xref std std-setting docutils literal notranslate"><span class="pre">DATABASES</span></code></a>.
These test databases are deleted when the tests are finished.</p>
<p>You will also need to ensure that your database uses UTF-8 as the default
character set. If your database server doesn't use UTF-8 as a default charset,
you will need to include a value for <a class="reference internal" href="../../../ref/settings.html#std:setting-TEST_CHARSET"><code class="xref std std-setting docutils literal notranslate"><span class="pre">CHARSET</span></code></a> in the
test settings dictionary for the applicable database.</p>
</div>
<div class="section" id="s-running-only-some-of-the-tests">
<span id="s-runtests-specifying-labels"></span><span id="running-only-some-of-the-tests"></span><span id="runtests-specifying-labels"></span><h3>执行一部分测试<a class="headerlink" href="#running-only-some-of-the-tests" title="永久链接至标题">¶</a></h3>
<p>Django的整个测试套件需要花一些时间才能运行，并且，例如，如果您刚刚向Django添加了一个想要快速运行而不运行其他所有功能的测试，则运行每个测试可能是多余的。您可以通过在命令行上将测试模块的名称附加到 <code class="docutils literal notranslate"><span class="pre">runtests.py</span></code> 上来运行单元测试的子集。</p>
<p>For example, if you'd like to run tests only for generic relations and
internationalization, type:</p>
<div class="console-block" id="console-block-5">
<input class="c-tab-unix" id="c-tab-5-unix" type="radio" name="console-5" checked>
<label for="c-tab-5-unix" title="Linux/macOS">&#xf17c/&#xf179</label>
<input class="c-tab-win" id="c-tab-5-win" type="radio" name="console-5">
<label for="c-tab-5-win" title="Windows">&#xf17a</label>
<section class="c-content-unix" id="c-content-5-unix">
<div class="highlight-console notranslate"><div class="highlight"><pre><span></span><span class="gp">$ </span>./runtests.py --settings<span class="o">=</span>path.to.settings generic_relations i18n
</pre></div>
</div>
</section>
<section class="c-content-win" id="c-content-5-win">
<div class="highlight"><pre><span></span><span class="gp">...\&gt;</span> runtests.py --settings=path.to.settings generic_relations i18n
</pre></div>
</section>
</div>
<p>How do you find out the names of individual tests? Look in <code class="docutils literal notranslate"><span class="pre">tests/</span></code> — each
directory name there is the name of a test.</p>
<p>If you want to run only a particular class of tests, you can specify a list of
paths to individual test classes. For example, to run the <code class="docutils literal notranslate"><span class="pre">TranslationTests</span></code>
of the <code class="docutils literal notranslate"><span class="pre">i18n</span></code> module, type:</p>
<div class="console-block" id="console-block-6">
<input class="c-tab-unix" id="c-tab-6-unix" type="radio" name="console-6" checked>
<label for="c-tab-6-unix" title="Linux/macOS">&#xf17c/&#xf179</label>
<input class="c-tab-win" id="c-tab-6-win" type="radio" name="console-6">
<label for="c-tab-6-win" title="Windows">&#xf17a</label>
<section class="c-content-unix" id="c-content-6-unix">
<div class="highlight-console notranslate"><div class="highlight"><pre><span></span><span class="gp">$ </span>./runtests.py --settings<span class="o">=</span>path.to.settings i18n.tests.TranslationTests
</pre></div>
</div>
</section>
<section class="c-content-win" id="c-content-6-win">
<div class="highlight"><pre><span></span><span class="gp">...\&gt;</span> runtests.py --settings=path.to.settings i18n.tests.TranslationTests
</pre></div>
</section>
</div>
<p>Going beyond that, you can specify an individual test method like this:</p>
<div class="console-block" id="console-block-7">
<input class="c-tab-unix" id="c-tab-7-unix" type="radio" name="console-7" checked>
<label for="c-tab-7-unix" title="Linux/macOS">&#xf17c/&#xf179</label>
<input class="c-tab-win" id="c-tab-7-win" type="radio" name="console-7">
<label for="c-tab-7-win" title="Windows">&#xf17a</label>
<section class="c-content-unix" id="c-content-7-unix">
<div class="highlight-console notranslate"><div class="highlight"><pre><span></span><span class="gp">$ </span>./runtests.py --settings<span class="o">=</span>path.to.settings i18n.tests.TranslationTests.test_lazy_objects
</pre></div>
</div>
</section>
<section class="c-content-win" id="c-content-7-win">
<div class="highlight"><pre><span></span><span class="gp">...\&gt;</span> runtests.py --settings=path.to.settings i18n.tests.TranslationTests.test_lazy_objects
</pre></div>
</section>
</div>
<p>You can run tests starting at a specified top-level module with <code class="docutils literal notranslate"><span class="pre">--start-at</span></code>
option. For example:</p>
<div class="console-block" id="console-block-8">
<input class="c-tab-unix" id="c-tab-8-unix" type="radio" name="console-8" checked>
<label for="c-tab-8-unix" title="Linux/macOS">&#xf17c/&#xf179</label>
<input class="c-tab-win" id="c-tab-8-win" type="radio" name="console-8">
<label for="c-tab-8-win" title="Windows">&#xf17a</label>
<section class="c-content-unix" id="c-content-8-unix">
<div class="highlight-console notranslate"><div class="highlight"><pre><span></span><span class="gp">$ </span>./runtests.py --start-at<span class="o">=</span>wsgi
</pre></div>
</div>
</section>
<section class="c-content-win" id="c-content-8-win">
<div class="highlight"><pre><span></span><span class="gp">...\&gt;</span> runtests.py --start-at=wsgi
</pre></div>
</section>
</div>
<p>You can also run tests starting after a specified top-level module with
<code class="docutils literal notranslate"><span class="pre">--start-after</span></code> option. For example:</p>
<div class="console-block" id="console-block-9">
<input class="c-tab-unix" id="c-tab-9-unix" type="radio" name="console-9" checked>
<label for="c-tab-9-unix" title="Linux/macOS">&#xf17c/&#xf179</label>
<input class="c-tab-win" id="c-tab-9-win" type="radio" name="console-9">
<label for="c-tab-9-win" title="Windows">&#xf17a</label>
<section class="c-content-unix" id="c-content-9-unix">
<div class="highlight-console notranslate"><div class="highlight"><pre><span></span><span class="gp">$ </span>./runtests.py --start-after<span class="o">=</span>wsgi
</pre></div>
</div>
</section>
<section class="c-content-win" id="c-content-9-win">
<div class="highlight"><pre><span></span><span class="gp">...\&gt;</span> runtests.py --start-after=wsgi
</pre></div>
</section>
</div>
<p>Note that the <code class="docutils literal notranslate"><span class="pre">--reverse</span></code> option doesn't impact on <code class="docutils literal notranslate"><span class="pre">--start-at</span></code> or
<code class="docutils literal notranslate"><span class="pre">--start-after</span></code> options. Moreover these options cannot be used with test
labels.</p>
</div>
<div class="section" id="s-running-the-selenium-tests">
<span id="running-the-selenium-tests"></span><h3>运行 Selenium&nbsp;测试<a class="headerlink" href="#running-the-selenium-tests" title="永久链接至标题">¶</a></h3>
<p>Some tests require Selenium and a Web browser. To run these tests, you must
install the <a class="reference external" href="https://pypi.org/project/selenium/">selenium</a> package and run the tests with the
<code class="docutils literal notranslate"><span class="pre">--selenium=&lt;BROWSERS&gt;</span></code> option. For example, if you have Firefox and Google
Chrome installed:</p>
<div class="console-block" id="console-block-10">
<input class="c-tab-unix" id="c-tab-10-unix" type="radio" name="console-10" checked>
<label for="c-tab-10-unix" title="Linux/macOS">&#xf17c/&#xf179</label>
<input class="c-tab-win" id="c-tab-10-win" type="radio" name="console-10">
<label for="c-tab-10-win" title="Windows">&#xf17a</label>
<section class="c-content-unix" id="c-content-10-unix">
<div class="highlight-console notranslate"><div class="highlight"><pre><span></span><span class="gp">$ </span>./runtests.py --selenium<span class="o">=</span>firefox,chrome
</pre></div>
</div>
</section>
<section class="c-content-win" id="c-content-10-win">
<div class="highlight"><pre><span></span><span class="gp">...\&gt;</span> runtests.py --selenium=firefox,chrome
</pre></div>
</section>
</div>
<p>See the <a class="reference external" href="https://github.com/SeleniumHQ/selenium/tree/trunk/py/selenium/webdriver">selenium.webdriver</a> package for the list of available browsers.</p>
<p>Specifying <code class="docutils literal notranslate"><span class="pre">--selenium</span></code> automatically sets <code class="docutils literal notranslate"><span class="pre">--tags=selenium</span></code> to run only
the tests that require selenium.</p>
<p>Some browsers (e.g. Chrome or Firefox) support headless testing, which can be
faster and more stable. Add the <code class="docutils literal notranslate"><span class="pre">--headless</span></code> option to enable this mode.</p>
</div>
<div class="section" id="s-running-all-the-tests">
<span id="s-running-unit-tests-dependencies"></span><span id="running-all-the-tests"></span><span id="running-unit-tests-dependencies"></span><h3>运行所有测试<a class="headerlink" href="#running-all-the-tests" title="永久链接至标题">¶</a></h3>
<p>如果要运行全套测试，则需要安装许多依赖项：</p>
<ul class="simple">
<li><a class="reference external" href="https://pypi.org/project/aiosmtpd/">aiosmtpd</a></li>
<li><a class="reference external" href="https://pypi.org/project/argon2-cffi/">argon2-cffi</a> 19.1.0+</li>
<li><a class="reference external" href="https://pypi.org/project/asgiref/">asgiref</a> 3.3.2+ (required)</li>
<li><a class="reference external" href="https://pypi.org/project/bcrypt/">bcrypt</a></li>
<li><a class="reference external" href="https://pypi.org/project/colorama/">colorama</a></li>
<li><a class="reference external" href="https://pypi.org/project/docutils/">docutils</a></li>
<li><a class="reference external" href="https://pypi.org/project/geoip2/">geoip2</a></li>
<li><a class="reference external" href="https://pypi.org/project/Jinja2/">jinja2</a> 2.7+</li>
<li><a class="reference external" href="https://pypi.org/project/numpy/">numpy</a></li>
<li><a class="reference external" href="https://pypi.org/project/Pillow/">Pillow</a> 6.2.0+</li>
<li><a class="reference external" href="https://pyyaml.org/wiki/PyYAML">PyYAML</a></li>
<li><a class="reference external" href="https://pypi.org/project/pytz/">pytz</a> (required)</li>
<li><a class="reference external" href="https://pypi.org/project/pywatchman/">pywatchman</a></li>
<li><a class="reference external" href="https://pypi.org/project/setuptools/">setuptools</a></li>
<li><a class="reference external" href="https://memcached.org/">memcached</a>, 加上:ref:<cite>supported Python binding &lt;memcached&gt;</cite></li>
<li><a class="reference external" href="https://www.gnu.org/software/gettext/manual/gettext.html">gettext</a> (<a class="reference internal" href="../../../topics/i18n/translation.html#gettext-on-windows"><span class="std std-ref">Windows 上的 gettext</span></a>)</li>
<li><a class="reference external" href="https://pypi.org/project/selenium/">selenium</a></li>
<li><a class="reference external" href="https://pypi.org/project/sqlparse/">sqlparse</a> 0.2.2+ (required)</li>
<li><a class="reference external" href="https://pypi.org/project/tblib/">tblib</a> 1.5.0+</li>
</ul>
<p>You can find these dependencies in <a class="reference external" href="https://pip.pypa.io/en/latest/user_guide/#requirements-files">pip requirements files</a> inside the
<code class="docutils literal notranslate"><span class="pre">tests/requirements</span></code> directory of the Django source tree and install them
like so:</p>
<div class="console-block" id="console-block-11">
<input class="c-tab-unix" id="c-tab-11-unix" type="radio" name="console-11" checked>
<label for="c-tab-11-unix" title="Linux/macOS">&#xf17c/&#xf179</label>
<input class="c-tab-win" id="c-tab-11-win" type="radio" name="console-11">
<label for="c-tab-11-win" title="Windows">&#xf17a</label>
<section class="c-content-unix" id="c-content-11-unix">
<div class="highlight-console notranslate"><div class="highlight"><pre><span></span><span class="gp">$ </span>python -m pip install -r tests/requirements/py3.txt
</pre></div>
</div>
</section>
<section class="c-content-win" id="c-content-11-win">
<div class="highlight"><pre><span></span><span class="gp">...\&gt;</span> py -m pip install -r tests\requirements\py3.txt
</pre></div>
</section>
</div>
<p>如果你在安装过程中发生了错误，可能是你的系统缺少一个或多个Python依赖包。请参考安装失败的包的文档或者在网上搜索错误的提示信息。</p>
<p>You can also install the database adapter(s) of your choice using
<code class="docutils literal notranslate"><span class="pre">oracle.txt</span></code>, <code class="docutils literal notranslate"><span class="pre">mysql.txt</span></code>, or <code class="docutils literal notranslate"><span class="pre">postgres.txt</span></code>.</p>
<p>如果要测试memcached缓存后端，则还需要定义一个指向您配置的memcached实例的 <a class="reference internal" href="../../../ref/settings.html#std:setting-CACHES"><code class="xref std std-setting docutils literal notranslate"><span class="pre">CACHES</span></code></a> 配置。</p>
<p>To run the GeoDjango tests, you will need to <a class="reference internal" href="../../../ref/contrib/gis/install/index.html"><span class="doc">setup a spatial database
and install the Geospatial libraries</span></a>.</p>
<p>这些依赖项中的每一个都是可选的。 如果您缺少其中的任何一个，则将跳过关联的测试。</p>
<p>To run some of the autoreload tests, you'll need to install the <a class="reference external" href="https://facebook.github.io/watchman/">Watchman</a>
service.</p>
</div>
<div class="section" id="s-code-coverage">
<span id="code-coverage"></span><h3>代码覆盖率<a class="headerlink" href="#code-coverage" title="永久链接至标题">¶</a></h3>
<p>鼓励贡献者对测试套件进行覆盖率测试，以确定需要额外测试的区域。在:ref:<cite>testing code coverage 1</cite>. 中介绍了coverage代码覆盖度工具的安装和使用。</p>
<p>Coverage should be run in a single process to obtain accurate statistics. To
run coverage on the Django test suite using the standard test settings:</p>
<div class="console-block" id="console-block-12">
<input class="c-tab-unix" id="c-tab-12-unix" type="radio" name="console-12" checked>
<label for="c-tab-12-unix" title="Linux/macOS">&#xf17c/&#xf179</label>
<input class="c-tab-win" id="c-tab-12-win" type="radio" name="console-12">
<label for="c-tab-12-win" title="Windows">&#xf17a</label>
<section class="c-content-unix" id="c-content-12-unix">
<div class="highlight-console notranslate"><div class="highlight"><pre><span></span><span class="gp">$ </span>coverage run ./runtests.py --settings<span class="o">=</span>test_sqlite --parallel<span class="o">=</span><span class="m">1</span>
</pre></div>
</div>
</section>
<section class="c-content-win" id="c-content-12-win">
<div class="highlight"><pre><span></span><span class="gp">...\&gt;</span> coverage run runtests.py --settings=test_sqlite --parallel=1
</pre></div>
</section>
</div>
<p>After running coverage, generate the html report by running:</p>
<div class="console-block" id="console-block-13">
<input class="c-tab-unix" id="c-tab-13-unix" type="radio" name="console-13" checked>
<label for="c-tab-13-unix" title="Linux/macOS">&#xf17c/&#xf179</label>
<input class="c-tab-win" id="c-tab-13-win" type="radio" name="console-13">
<label for="c-tab-13-win" title="Windows">&#xf17a</label>
<section class="c-content-unix" id="c-content-13-unix">
<div class="highlight-console notranslate"><div class="highlight"><pre><span></span><span class="gp">$ </span>coverage html
</pre></div>
</div>
</section>
<section class="c-content-win" id="c-content-13-win">
<div class="highlight"><pre><span></span><span class="gp">...\&gt;</span> coverage html
</pre></div>
</section>
</div>
<p>运行Django测试的覆盖率时，随附的 <code class="docutils literal notranslate"><span class="pre">.coveragerc</span></code> 配置文件将 <code class="docutils literal notranslate"><span class="pre">coverage_html</span></code> 定义为报告的输出目录，并且还排除了与结果无关的几个目录（Django中包含的测试代码或外部代码）。</p>
</div>
</div>
<div class="section" id="s-contrib-apps">
<span id="s-id1"></span><span id="contrib-apps"></span><span id="id1"></span><h2>Contrib 应用程序<a class="headerlink" href="#contrib-apps" title="永久链接至标题">¶</a></h2>
<p>Tests for contrib apps can be found in the <code class="docutils literal notranslate"><span class="pre">tests/</span></code> directory, typically
under <code class="docutils literal notranslate"><span class="pre">&lt;app_name&gt;_tests</span></code>. For example, tests for <code class="docutils literal notranslate"><span class="pre">contrib.auth</span></code> are located
in <code class="docutils literal notranslate"><span class="pre">tests/auth_tests</span></code>.</p>
</div>
<div class="section" id="s-troubleshooting">
<span id="s-troubleshooting-unit-tests"></span><span id="troubleshooting"></span><span id="troubleshooting-unit-tests"></span><h2>错误调试<a class="headerlink" href="#troubleshooting" title="永久链接至标题">¶</a></h2>
<div class="section" id="s-test-suite-hangs-or-shows-failures-on-main-branch">
<span id="test-suite-hangs-or-shows-failures-on-main-branch"></span><h3>Test suite hangs or shows failures on <code class="docutils literal notranslate"><span class="pre">main</span></code> branch<a class="headerlink" href="#test-suite-hangs-or-shows-failures-on-main-branch" title="永久链接至标题">¶</a></h3>
<p>Ensure you have the latest point release of a <a class="reference internal" href="../../../faq/install.html#faq-python-version-support"><span class="std std-ref">supported Python version</span></a>, since there are often bugs in earlier versions
that may cause the test suite to fail or hang.</p>
<p>On <strong>macOS</strong> (High Sierra and newer versions), you might see this message
logged, after which the tests hang:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">objc</span><span class="p">[</span><span class="mi">42074</span><span class="p">]:</span> <span class="o">+</span><span class="p">[</span><span class="n">__NSPlaceholderDate</span> <span class="n">initialize</span><span class="p">]</span> <span class="n">may</span> <span class="n">have</span> <span class="n">been</span> <span class="ow">in</span> <span class="n">progress</span> <span class="ow">in</span>
<span class="n">another</span> <span class="n">thread</span> <span class="n">when</span> <span class="n">fork</span><span class="p">()</span> <span class="n">was</span> <span class="n">called</span><span class="o">.</span>
</pre></div>
</div>
<p>To avoid this set a <code class="docutils literal notranslate"><span class="pre">OBJC_DISABLE_INITIALIZE_FORK_SAFETY</span></code> environment
variable, for example:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span>$ OBJC_DISABLE_INITIALIZE_FORK_SAFETY=YES ./runtests.py
</pre></div>
</div>
<p>Or add <code class="docutils literal notranslate"><span class="pre">export</span> <span class="pre">OBJC_DISABLE_INITIALIZE_FORK_SAFETY=YES</span></code> to your shell's
startup file (e.g. <code class="docutils literal notranslate"><span class="pre">~/.profile</span></code>).</p>
</div>
<div class="section" id="s-many-test-failures-with-unicodeencodeerror">
<span id="many-test-failures-with-unicodeencodeerror"></span><h3>Many test failures with <code class="docutils literal notranslate"><span class="pre">UnicodeEncodeError</span></code><a class="headerlink" href="#many-test-failures-with-unicodeencodeerror" title="永久链接至标题">¶</a></h3>
<p>If the <code class="docutils literal notranslate"><span class="pre">locales</span></code> package is not installed, some tests will fail with a
<code class="docutils literal notranslate"><span class="pre">UnicodeEncodeError</span></code>.</p>
<p>You can resolve this on Debian-based systems, for example, by running:</p>
<div class="highlight-console notranslate"><div class="highlight"><pre><span></span><span class="gp">$ </span>apt-get install locales
<span class="gp">$ </span>dpkg-reconfigure locales
</pre></div>
</div>
<p>You can resolve this for macOS systems by configuring your shell's locale:</p>
<div class="highlight-console notranslate"><div class="highlight"><pre><span></span><span class="gp">$ </span><span class="nb">export</span> <span class="nv">LANG</span><span class="o">=</span><span class="s2">&quot;en_US.UTF-8&quot;</span>
<span class="gp">$ </span><span class="nb">export</span> <span class="nv">LC_ALL</span><span class="o">=</span><span class="s2">&quot;en_US.UTF-8&quot;</span>
</pre></div>
</div>
<p>Run the <code class="docutils literal notranslate"><span class="pre">locale</span></code> command to confirm the change. Optionally, add those export
commands to your shell's startup file (e.g. <code class="docutils literal notranslate"><span class="pre">~/.bashrc</span></code> for Bash) to avoid
having to retype them.</p>
</div>
<div class="section" id="s-tests-that-only-fail-in-combination">
<span id="tests-that-only-fail-in-combination"></span><h3>Tests that only fail in combination<a class="headerlink" href="#tests-that-only-fail-in-combination" title="永久链接至标题">¶</a></h3>
<p>In case a test passes when run in isolation but fails within the whole suite,
we have some tools to help analyze the problem.</p>
<p>The <code class="docutils literal notranslate"><span class="pre">--bisect</span></code> option of <code class="docutils literal notranslate"><span class="pre">runtests.py</span></code> will run the failing test while
halving the test set it is run together with on each iteration, often making
it possible to identify a small number of tests that may be related to the
failure.</p>
<p>For example, suppose that the failing test that works on its own is
<code class="docutils literal notranslate"><span class="pre">ModelTest.test_eq</span></code>, then using:</p>
<div class="console-block" id="console-block-14">
<input class="c-tab-unix" id="c-tab-14-unix" type="radio" name="console-14" checked>
<label for="c-tab-14-unix" title="Linux/macOS">&#xf17c/&#xf179</label>
<input class="c-tab-win" id="c-tab-14-win" type="radio" name="console-14">
<label for="c-tab-14-win" title="Windows">&#xf17a</label>
<section class="c-content-unix" id="c-content-14-unix">
<div class="highlight-console notranslate"><div class="highlight"><pre><span></span><span class="gp">$ </span>./runtests.py --bisect basic.tests.ModelTest.test_eq
</pre></div>
</div>
</section>
<section class="c-content-win" id="c-content-14-win">
<div class="highlight"><pre><span></span><span class="gp">...\&gt;</span> runtests.py --bisect basic.tests.ModelTest.test_eq
</pre></div>
</section>
</div>
<p>will try to determine a test that interferes with the given one. First, the
test is run with the first half of the test suite. If a failure occurs, the
first half of the test suite is split in two groups and each group is then run
with the specified test. If there is no failure with the first half of the test
suite, the second half of the test suite is run with the specified test and
split appropriately as described earlier. The process repeats until the set of
failing tests is minimized.</p>
<p>The <code class="docutils literal notranslate"><span class="pre">--pair</span></code> option runs the given test alongside every other test from the
suite, letting you check if another test has side-effects that cause the
failure. So:</p>
<div class="console-block" id="console-block-15">
<input class="c-tab-unix" id="c-tab-15-unix" type="radio" name="console-15" checked>
<label for="c-tab-15-unix" title="Linux/macOS">&#xf17c/&#xf179</label>
<input class="c-tab-win" id="c-tab-15-win" type="radio" name="console-15">
<label for="c-tab-15-win" title="Windows">&#xf17a</label>
<section class="c-content-unix" id="c-content-15-unix">
<div class="highlight-console notranslate"><div class="highlight"><pre><span></span><span class="gp">$ </span>./runtests.py --pair basic.tests.ModelTest.test_eq
</pre></div>
</div>
</section>
<section class="c-content-win" id="c-content-15-win">
<div class="highlight"><pre><span></span><span class="gp">...\&gt;</span> runtests.py --pair basic.tests.ModelTest.test_eq
</pre></div>
</section>
</div>
<p>will pair <code class="docutils literal notranslate"><span class="pre">test_eq</span></code> with every test label.</p>
<p>With both <code class="docutils literal notranslate"><span class="pre">--bisect</span></code> and <code class="docutils literal notranslate"><span class="pre">--pair</span></code>, if you already suspect which cases
might be responsible for the failure, you may limit tests to be cross-analyzed
by <a class="reference internal" href="#runtests-specifying-labels"><span class="std std-ref">specifying further test labels</span></a> after
the first one:</p>
<div class="console-block" id="console-block-16">
<input class="c-tab-unix" id="c-tab-16-unix" type="radio" name="console-16" checked>
<label for="c-tab-16-unix" title="Linux/macOS">&#xf17c/&#xf179</label>
<input class="c-tab-win" id="c-tab-16-win" type="radio" name="console-16">
<label for="c-tab-16-win" title="Windows">&#xf17a</label>
<section class="c-content-unix" id="c-content-16-unix">
<div class="highlight-console notranslate"><div class="highlight"><pre><span></span><span class="gp">$ </span>./runtests.py --pair basic.tests.ModelTest.test_eq queries transactions
</pre></div>
</div>
</section>
<section class="c-content-win" id="c-content-16-win">
<div class="highlight"><pre><span></span><span class="gp">...\&gt;</span> runtests.py --pair basic.tests.ModelTest.test_eq queries transactions
</pre></div>
</section>
</div>
<p>You can also try running any set of tests in reverse using the <code class="docutils literal notranslate"><span class="pre">--reverse</span></code>
option in order to verify that executing tests in a different order does not
cause any trouble:</p>
<div class="console-block" id="console-block-17">
<input class="c-tab-unix" id="c-tab-17-unix" type="radio" name="console-17" checked>
<label for="c-tab-17-unix" title="Linux/macOS">&#xf17c/&#xf179</label>
<input class="c-tab-win" id="c-tab-17-win" type="radio" name="console-17">
<label for="c-tab-17-win" title="Windows">&#xf17a</label>
<section class="c-content-unix" id="c-content-17-unix">
<div class="highlight-console notranslate"><div class="highlight"><pre><span></span><span class="gp">$ </span>./runtests.py basic --reverse
</pre></div>
</div>
</section>
<section class="c-content-win" id="c-content-17-win">
<div class="highlight"><pre><span></span><span class="gp">...\&gt;</span> runtests.py basic --reverse
</pre></div>
</section>
</div>
</div>
<div class="section" id="s-seeing-the-sql-queries-run-during-a-test">
<span id="seeing-the-sql-queries-run-during-a-test"></span><h3>Seeing the SQL queries run during a test<a class="headerlink" href="#seeing-the-sql-queries-run-during-a-test" title="永久链接至标题">¶</a></h3>
<p>If you wish to examine the SQL being run in failing tests, you can turn on
<a class="reference internal" href="../../../topics/logging.html#django-db-logger"><span class="std std-ref">SQL logging</span></a> using the <code class="docutils literal notranslate"><span class="pre">--debug-sql</span></code> option. If you
combine this with <code class="docutils literal notranslate"><span class="pre">--verbosity=2</span></code>, all SQL queries will be output:</p>
<div class="console-block" id="console-block-18">
<input class="c-tab-unix" id="c-tab-18-unix" type="radio" name="console-18" checked>
<label for="c-tab-18-unix" title="Linux/macOS">&#xf17c/&#xf179</label>
<input class="c-tab-win" id="c-tab-18-win" type="radio" name="console-18">
<label for="c-tab-18-win" title="Windows">&#xf17a</label>
<section class="c-content-unix" id="c-content-18-unix">
<div class="highlight-console notranslate"><div class="highlight"><pre><span></span><span class="gp">$ </span>./runtests.py basic --debug-sql
</pre></div>
</div>
</section>
<section class="c-content-win" id="c-content-18-win">
<div class="highlight"><pre><span></span><span class="gp">...\&gt;</span> runtests.py basic --debug-sql
</pre></div>
</section>
</div>
</div>
<div class="section" id="s-seeing-the-full-traceback-of-a-test-failure">
<span id="seeing-the-full-traceback-of-a-test-failure"></span><h3>Seeing the full traceback of a test failure<a class="headerlink" href="#seeing-the-full-traceback-of-a-test-failure" title="永久链接至标题">¶</a></h3>
<p>By default tests are run in parallel with one process per core. When the tests
are run in parallel, however, you'll only see a truncated traceback for any
test failures. You can adjust this behavior with the <code class="docutils literal notranslate"><span class="pre">--parallel</span></code> option:</p>
<div class="console-block" id="console-block-19">
<input class="c-tab-unix" id="c-tab-19-unix" type="radio" name="console-19" checked>
<label for="c-tab-19-unix" title="Linux/macOS">&#xf17c/&#xf179</label>
<input class="c-tab-win" id="c-tab-19-win" type="radio" name="console-19">
<label for="c-tab-19-win" title="Windows">&#xf17a</label>
<section class="c-content-unix" id="c-content-19-unix">
<div class="highlight-console notranslate"><div class="highlight"><pre><span></span><span class="gp">$ </span>./runtests.py basic --parallel<span class="o">=</span><span class="m">1</span>
</pre></div>
</div>
</section>
<section class="c-content-win" id="c-content-19-win">
<div class="highlight"><pre><span></span><span class="gp">...\&gt;</span> runtests.py basic --parallel=1
</pre></div>
</section>
</div>
<p>You can also use the <span class="target" id="index-2"></span><a class="reference internal" href="../../../ref/django-admin.html#envvar-DJANGO_TEST_PROCESSES"><code class="xref std std-envvar docutils literal notranslate"><span class="pre">DJANGO_TEST_PROCESSES</span></code></a> environment variable for
this purpose.</p>
</div>
</div>
<div class="section" id="s-tips-for-writing-tests">
<span id="tips-for-writing-tests"></span><h2>Tips for writing tests<a class="headerlink" href="#tips-for-writing-tests" title="永久链接至标题">¶</a></h2>
<div class="section" id="s-isolating-model-registration">
<span id="isolating-model-registration"></span><h3>Isolating model registration<a class="headerlink" href="#isolating-model-registration" title="永久链接至标题">¶</a></h3>
<p>To avoid polluting the global <a class="reference internal" href="../../../ref/applications.html#django.apps.apps" title="django.apps.apps"><code class="xref py py-attr docutils literal notranslate"><span class="pre">apps</span></code></a> registry and prevent
unnecessary table creation, models defined in a test method should be bound to
a temporary <code class="docutils literal notranslate"><span class="pre">Apps</span></code> instance:</p>
<div class="highlight-python notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">django.apps.registry</span> <span class="kn">import</span> <span class="n">Apps</span>
<span class="kn">from</span> <span class="nn">django.db</span> <span class="kn">import</span> <span class="n">models</span>
<span class="kn">from</span> <span class="nn">django.test</span> <span class="kn">import</span> <span class="n">SimpleTestCase</span>

<span class="k">class</span> <span class="nc">TestModelDefinition</span><span class="p">(</span><span class="n">SimpleTestCase</span><span class="p">):</span>
    <span class="k">def</span> <span class="nf">test_model_definition</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
        <span class="n">test_apps</span> <span class="o">=</span> <span class="n">Apps</span><span class="p">([</span><span class="s1">&#39;app_label&#39;</span><span class="p">])</span>

        <span class="k">class</span> <span class="nc">TestModel</span><span class="p">(</span><span class="n">models</span><span class="o">.</span><span class="n">Model</span><span class="p">):</span>
            <span class="k">class</span> <span class="nc">Meta</span><span class="p">:</span>
                <span class="n">apps</span> <span class="o">=</span> <span class="n">test_apps</span>
        <span class="o">...</span>
</pre></div>
</div>
<dl class="function">
<dt id="django.test.utils.isolate_apps">
<code class="descclassname">django.test.utils.</code><code class="descname">isolate_apps</code>(<em>*app_labels</em>, <em>attr_name=None</em>, <em>kwarg_name=None</em>)<a class="headerlink" href="#django.test.utils.isolate_apps" title="永久链接至目标">¶</a></dt>
<dd></dd></dl>

<p>Since this pattern involves a lot of boilerplate, Django provides the
<a class="reference internal" href="#django.test.utils.isolate_apps" title="django.test.utils.isolate_apps"><code class="xref py py-func docutils literal notranslate"><span class="pre">isolate_apps()</span></code></a> decorator. It's used like this:</p>
<div class="highlight-python notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">django.db</span> <span class="kn">import</span> <span class="n">models</span>
<span class="kn">from</span> <span class="nn">django.test</span> <span class="kn">import</span> <span class="n">SimpleTestCase</span>
<span class="kn">from</span> <span class="nn">django.test.utils</span> <span class="kn">import</span> <span class="n">isolate_apps</span>

<span class="k">class</span> <span class="nc">TestModelDefinition</span><span class="p">(</span><span class="n">SimpleTestCase</span><span class="p">):</span>
    <span class="nd">@isolate_apps</span><span class="p">(</span><span class="s1">&#39;app_label&#39;</span><span class="p">)</span>
    <span class="k">def</span> <span class="nf">test_model_definition</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
        <span class="k">class</span> <span class="nc">TestModel</span><span class="p">(</span><span class="n">models</span><span class="o">.</span><span class="n">Model</span><span class="p">):</span>
            <span class="k">pass</span>
        <span class="o">...</span>
</pre></div>
</div>
<div class="admonition-setting-app-label admonition">
<p class="first admonition-title">Setting <code class="docutils literal notranslate"><span class="pre">app_label</span></code></p>
<p>Models defined in a test method with no explicit
<a class="reference internal" href="../../../ref/models/options.html#django.db.models.Options.app_label" title="django.db.models.Options.app_label"><code class="xref py py-attr docutils literal notranslate"><span class="pre">app_label</span></code></a> are automatically assigned the
label of the app in which their test class is located.</p>
<p>In order to make sure the models defined within the context of
<a class="reference internal" href="#django.test.utils.isolate_apps" title="django.test.utils.isolate_apps"><code class="xref py py-func docutils literal notranslate"><span class="pre">isolate_apps()</span></code></a> instances are correctly
installed, you should pass the set of targeted <code class="docutils literal notranslate"><span class="pre">app_label</span></code> as arguments:</p>
<div class="literal-block-wrapper last docutils container" id="id2">
<div class="code-block-caption"><span class="caption-text">tests/app_label/tests.py</span><a class="headerlink" href="#id2" title="永久链接至代码">¶</a></div>
<div class="highlight-python notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">django.db</span> <span class="kn">import</span> <span class="n">models</span>
<span class="kn">from</span> <span class="nn">django.test</span> <span class="kn">import</span> <span class="n">SimpleTestCase</span>
<span class="kn">from</span> <span class="nn">django.test.utils</span> <span class="kn">import</span> <span class="n">isolate_apps</span>

<span class="k">class</span> <span class="nc">TestModelDefinition</span><span class="p">(</span><span class="n">SimpleTestCase</span><span class="p">):</span>
    <span class="nd">@isolate_apps</span><span class="p">(</span><span class="s1">&#39;app_label&#39;</span><span class="p">,</span> <span class="s1">&#39;other_app_label&#39;</span><span class="p">)</span>
    <span class="k">def</span> <span class="nf">test_model_definition</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
        <span class="c1"># This model automatically receives app_label=&#39;app_label&#39;</span>
        <span class="k">class</span> <span class="nc">TestModel</span><span class="p">(</span><span class="n">models</span><span class="o">.</span><span class="n">Model</span><span class="p">):</span>
            <span class="k">pass</span>

        <span class="k">class</span> <span class="nc">OtherAppModel</span><span class="p">(</span><span class="n">models</span><span class="o">.</span><span class="n">Model</span><span class="p">):</span>
            <span class="k">class</span> <span class="nc">Meta</span><span class="p">:</span>
                <span class="n">app_label</span> <span class="o">=</span> <span class="s1">&#39;other_app_label&#39;</span>
        <span class="o">...</span>
</pre></div>
</div>
</div>
</div>
<p>The decorator can also be applied to classes:</p>
<div class="highlight-python notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">django.db</span> <span class="kn">import</span> <span class="n">models</span>
<span class="kn">from</span> <span class="nn">django.test</span> <span class="kn">import</span> <span class="n">SimpleTestCase</span>
<span class="kn">from</span> <span class="nn">django.test.utils</span> <span class="kn">import</span> <span class="n">isolate_apps</span>

<span class="nd">@isolate_apps</span><span class="p">(</span><span class="s1">&#39;app_label&#39;</span><span class="p">)</span>
<span class="k">class</span> <span class="nc">TestModelDefinition</span><span class="p">(</span><span class="n">SimpleTestCase</span><span class="p">):</span>
    <span class="k">def</span> <span class="nf">test_model_definition</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
        <span class="k">class</span> <span class="nc">TestModel</span><span class="p">(</span><span class="n">models</span><span class="o">.</span><span class="n">Model</span><span class="p">):</span>
            <span class="k">pass</span>
        <span class="o">...</span>
</pre></div>
</div>
<p>The temporary <code class="docutils literal notranslate"><span class="pre">Apps</span></code> instance used to isolate model registration can be
retrieved as an attribute when used as a class decorator by using the
<code class="docutils literal notranslate"><span class="pre">attr_name</span></code> parameter:</p>
<div class="highlight-python notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">django.db</span> <span class="kn">import</span> <span class="n">models</span>
<span class="kn">from</span> <span class="nn">django.test</span> <span class="kn">import</span> <span class="n">SimpleTestCase</span>
<span class="kn">from</span> <span class="nn">django.test.utils</span> <span class="kn">import</span> <span class="n">isolate_apps</span>

<span class="nd">@isolate_apps</span><span class="p">(</span><span class="s1">&#39;app_label&#39;</span><span class="p">,</span> <span class="n">attr_name</span><span class="o">=</span><span class="s1">&#39;apps&#39;</span><span class="p">)</span>
<span class="k">class</span> <span class="nc">TestModelDefinition</span><span class="p">(</span><span class="n">SimpleTestCase</span><span class="p">):</span>
    <span class="k">def</span> <span class="nf">test_model_definition</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
        <span class="k">class</span> <span class="nc">TestModel</span><span class="p">(</span><span class="n">models</span><span class="o">.</span><span class="n">Model</span><span class="p">):</span>
            <span class="k">pass</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">assertIs</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">apps</span><span class="o">.</span><span class="n">get_model</span><span class="p">(</span><span class="s1">&#39;app_label&#39;</span><span class="p">,</span> <span class="s1">&#39;TestModel&#39;</span><span class="p">),</span> <span class="n">TestModel</span><span class="p">)</span>
</pre></div>
</div>
<p>Or as an argument on the test method when used as a method decorator by using
the <code class="docutils literal notranslate"><span class="pre">kwarg_name</span></code> parameter:</p>
<div class="highlight-python notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">django.db</span> <span class="kn">import</span> <span class="n">models</span>
<span class="kn">from</span> <span class="nn">django.test</span> <span class="kn">import</span> <span class="n">SimpleTestCase</span>
<span class="kn">from</span> <span class="nn">django.test.utils</span> <span class="kn">import</span> <span class="n">isolate_apps</span>

<span class="k">class</span> <span class="nc">TestModelDefinition</span><span class="p">(</span><span class="n">SimpleTestCase</span><span class="p">):</span>
    <span class="nd">@isolate_apps</span><span class="p">(</span><span class="s1">&#39;app_label&#39;</span><span class="p">,</span> <span class="n">kwarg_name</span><span class="o">=</span><span class="s1">&#39;apps&#39;</span><span class="p">)</span>
    <span class="k">def</span> <span class="nf">test_model_definition</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">apps</span><span class="p">):</span>
        <span class="k">class</span> <span class="nc">TestModel</span><span class="p">(</span><span class="n">models</span><span class="o">.</span><span class="n">Model</span><span class="p">):</span>
            <span class="k">pass</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">assertIs</span><span class="p">(</span><span class="n">apps</span><span class="o">.</span><span class="n">get_model</span><span class="p">(</span><span class="s1">&#39;app_label&#39;</span><span class="p">,</span> <span class="s1">&#39;TestModel&#39;</span><span class="p">),</span> <span class="n">TestModel</span><span class="p">)</span>
</pre></div>
</div>
</div>
</div>
</div>


          </div>
        </div>
      </div>
      
        
          <div class="yui-b" id="sidebar">
            
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h3><a href="../../../contents.html">Table of Contents</a></h3>
  <ul>
<li><a class="reference internal" href="#">单元测试集</a><ul>
<li><a class="reference internal" href="#running-the-unit-tests">运行单元测试</a><ul>
<li><a class="reference internal" href="#quickstart">快速上手</a></li>
<li><a class="reference internal" href="#running-tests-using-tox">Running tests using <code class="docutils literal notranslate"><span class="pre">tox</span></code></a><ul>
<li><a class="reference internal" href="#testing-other-python-versions-and-database-backends">Testing other Python versions and database backends</a></li>
<li><a class="reference internal" href="#running-the-javascript-tests">运行 JavaScript 测试集</a></li>
</ul>
</li>
<li><a class="reference internal" href="#running-tests-using-django-docker-box">Running tests using <code class="docutils literal notranslate"><span class="pre">django-docker-box</span></code></a></li>
<li><a class="reference internal" href="#using-another-settings-module">使用另一个 <code class="docutils literal notranslate"><span class="pre">settings</span></code> 配置模块</a></li>
<li><a class="reference internal" href="#running-only-some-of-the-tests">执行一部分测试</a></li>
<li><a class="reference internal" href="#running-the-selenium-tests">运行 Selenium&nbsp;测试</a></li>
<li><a class="reference internal" href="#running-all-the-tests">运行所有测试</a></li>
<li><a class="reference internal" href="#code-coverage">代码覆盖率</a></li>
</ul>
</li>
<li><a class="reference internal" href="#contrib-apps">Contrib 应用程序</a></li>
<li><a class="reference internal" href="#troubleshooting">错误调试</a><ul>
<li><a class="reference internal" href="#test-suite-hangs-or-shows-failures-on-main-branch">Test suite hangs or shows failures on <code class="docutils literal notranslate"><span class="pre">main</span></code> branch</a></li>
<li><a class="reference internal" href="#many-test-failures-with-unicodeencodeerror">Many test failures with <code class="docutils literal notranslate"><span class="pre">UnicodeEncodeError</span></code></a></li>
<li><a class="reference internal" href="#tests-that-only-fail-in-combination">Tests that only fail in combination</a></li>
<li><a class="reference internal" href="#seeing-the-sql-queries-run-during-a-test">Seeing the SQL queries run during a test</a></li>
<li><a class="reference internal" href="#seeing-the-full-traceback-of-a-test-failure">Seeing the full traceback of a test failure</a></li>
</ul>
</li>
<li><a class="reference internal" href="#tips-for-writing-tests">Tips for writing tests</a><ul>
<li><a class="reference internal" href="#isolating-model-registration">Isolating model registration</a></li>
</ul>
</li>
</ul>
</li>
</ul>

  <h4>上一个主题</h4>
  <p class="topless"><a href="coding-style.html"
                        title="上一章">编码风格</a></p>
  <h4>下一个主题</h4>
  <p class="topless"><a href="submitting-patches.html"
                        title="下一章">提交补丁</a></p>
  <div role="note" aria-label="source link">
    <h3>本页</h3>
    <ul class="this-page-menu">
      <li><a href="../../../_sources/internals/contributing/writing-code/unit-tests.txt"
            rel="nofollow">显示源代码</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>快速搜索</h3>
    <div class="searchformwrapper">
    <form class="search" action="../../../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="转向" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
              <h3>Last update:</h3>
              <p class="topless">12月 07, 2021</p>
          </div>
        
      
    </div>

    <div id="ft">
      <div class="nav">
    &laquo; <a href="coding-style.html" title="编码风格">previous</a>
     |
    <a href="../../index.html" title="Django internals" accesskey="U">up</a>
   |
    <a href="submitting-patches.html" title="提交补丁">next</a> &raquo;</div>
    </div>
  </div>

      <div class="clearer"></div>
    </div>
  </body>
</html>